package cn.dida.dao;

import java.util.List;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.stereotype.Repository;

import cn.dida.model.LogSendShortMsg;
import cn.dida.model.Pageable;

/**
 * 短信日志 数据交互类
 * @author weiwei
 */
@Repository
public class LogSendShortMsgDao extends DaoBase {
	/**
	 * 短信日志列表
	 * @param companyId 公司id
	 * @param keyword 查询条件
	 * @param timeLimitStart 发送时间(开始)
	 * @param timeLimitEnd 发送时间(结束)
	 * @param page 分页游标
	 * @return Pageable<LogSendShortMsg> 短信日志分页列表
	 */
    public Pageable<LogSendShortMsg> queryLog(Integer companyId, String keyword, Long timeLimitStart, Long timeLimitEnd, int page) {
        Object[] args = {};
        StringBuffer sqlQueryResultCount = new StringBuffer("select count(1) from log_send_short_msg t1 join company t2 on t1.company_id = t2.id");
        StringBuffer sqlQueryResult = new StringBuffer("select t1.*, t2.name 'companyName' from log_send_short_msg t1 join company t2 on t1.company_id = t2.id");

        StringBuffer sqlWhere = new StringBuffer(" where t1.company_id = ?");
        args = ArrayUtils.add(args, companyId);
        if (StringUtils.isNotBlank(keyword)) {
            sqlWhere.append(" and t2.name  like ?");
            args = ArrayUtils.add(args, "%" + keyword + "%");
        }
        if (timeLimitStart != null) {
            sqlWhere.append(" and t1.c_time >= ?");
            args = ArrayUtils.add(args, timeLimitStart);
        }
        if (timeLimitEnd != null) {
            sqlWhere.append(" and t1.c_time <= ?");
            args = ArrayUtils.add(args, timeLimitEnd);
        }

        // 查询记录总数
        Integer resultTotal = jdbcTemplate.queryForObject(sqlQueryResultCount.append(sqlWhere).toString(), Integer.class, args);
        // 查询记录
        sqlQueryResult.append(sqlWhere).append("  order by t1.c_time desc limit ?,?");
        args = ArrayUtils.add(args, (page - 1) * getPageSize());
        args = ArrayUtils.add(args, getPageSize());

        List<LogSendShortMsg> result = jdbcTemplate.query(sqlQueryResult.toString(), args, new BeanPropertyRowMapper<>(LogSendShortMsg.class));
        return new Pageable<LogSendShortMsg>(page, getPageSize(), resultTotal, result);
    }

}